<template>
  <div class="form-designer">
    <el-card>
      <template #header>
        <div class="designer-header">
          <span class="form-name">{{ name }}</span>
          <div class="header-actions">
            <div class="header-options">
              <el-tooltip content="导出 Word 时使用横向纸张（仅当前表单）" placement="bottom">
                <el-check-tag :checked="isLandscape" @change="setLandscape">
                  <el-icon><Rank /></el-icon>
                  <span class="tag-text">横向纸张</span>
                </el-check-tag>
              </el-tooltip>
              <el-tooltip content="该表单导出时独占页面，前后自动分页" placement="bottom">
                <el-check-tag :checked="isSinglePage" @change="setSinglePage">
                  <el-icon><Document /></el-icon>
                  <span class="tag-text">单页</span>
                </el-check-tag>
              </el-tooltip>
            </div>
            <el-button type="primary" @click="handleSave" :loading="saving">
              {{ saving ? '保存中...' : '保存' }}
            </el-button>
            <el-button @click="handlePreview">预览</el-button>
            <el-button @click="handleViewJson">查看JSON</el-button>
            <el-button @click="handleClose">关闭</el-button>
          </div>
        </div>
      </template>

      <div class="designer-content">
        <div class="fields-panel">
          <el-card class="fields-list">
            <template #header>
              <div class="panel-header">组件</div>
            </template>
            <div 
              v-for="field in fieldTypes" 
              :key="field.type"
              class="field-item"
              draggable="true"
              @dragstart="handleDragStart($event, field)"
              @dragend="handleDragEnd"
            >
              <el-icon><component :is="field.icon" /></el-icon>
              <span>{{ field.label }}</span>
            </div>
          </el-card>
        </div>

        <div 
          ref="canvasRef"
          class="form-canvas"
          @dragover.prevent
          @dragenter.prevent="handleDragEnter"
          @dragleave.prevent="handleDragLeave"
          @drop="handleDrop"
        >
          <template v-if="formFields.length">
            <div 
              v-for="(field, index) in formFields" 
              :key="field.id"
              class="form-field"
              :class="{ 'is-selected': selectedField?.id === field.id }"
              @click="handleSelectField(field)"
            >
              <div class="field-content">
                <!-- 日期时间组合字段 -->
                <template v-if="field.type === 'dateTimeGroup'">
                  <DateTimeGroup 
                    v-model="field.value"
                    :suffix="field.suffix"
                  />
                </template>

                <!-- 其他字段类型 -->
                <template v-else-if="field.type === 'radioWithInput'">
                  <RadioWithInput 
                    v-model="field.value"
                  />
                </template>





                <!-- 表格字段 -->
                <template v-else-if="field.type === 'criteriaTable'">
                  <CriteriaTable 
                    v-model="field.value"
                  />
                </template>



                <!-- 横向选项字段 -->
                <template v-else-if="field.type === 'horizontalOptions'">
                  <HorizontalOptions 
                    v-model="field.value"
                  />
                </template>

                <!-- 竖向选项字段 -->
                <template v-else-if="field.type === 'verticalOptions'">
                  <VerticalOptions 
                    v-model="field.value"
                  />
                </template>

                <!-- 粘贴单 -->
                <template v-else-if="field.type === 'pasteUnit'">
                  <PasteUnit
                    v-model="field.value"
                  />
                </template>


                <!-- 签字日期 -->
                <template v-else-if="field.type === 'signatureDate'">
                  <SignatureDateField
                    v-model="field.value"
                  />
                </template>

                <!-- 其他字段类型 -->
                <template v-else>
                  <component 
                    :is="getComponentByType(field.type)" 
                    v-bind="field.props"
                    v-model="field.value"
                  />
                </template>
              </div>
              
              <div class="field-actions">
                <el-button-group>
                  <el-button 
                    link 
                    type="primary" 
                    size="small"
                    @click.stop="handleMoveField(index, -1)"
                    :disabled="index === 0"
                  >
                    <el-icon><ArrowUp /></el-icon>
                  </el-button>
                  <el-button 
                    link 
                    type="primary" 
                    size="small"
                    @click.stop="handleMoveField(index, 1)"
                    :disabled="index === formFields.length - 1"
                  >
                    <el-icon><ArrowDown /></el-icon>
                  </el-button>
                  <el-button 
                    link 
                    type="danger" 
                    size="small"
                    @click.stop="handleDeleteField(index)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>
          <div v-else class="empty-tip">
            从左侧拖拽字段到这里
          </div>
        </div>

        <div class="properties-panel" v-if="selectedField">
          <el-card class="properties-form">
            <template #header>
              <div class="panel-header">{{ selectedField.type === 'criteriaTable' ? '表格属性' : '字段属性' }}</div>
            </template>
            
            <el-form label-position="top">
              <el-form-item label="字段OID">
                <el-input :model-value="selectedField.id" readonly disabled />
              </el-form-item>
              <el-form-item label="字段标识" style="display: none;">
                <el-input v-model="selectedField.name" />
              </el-form-item>
              
              <!-- 签字日期特有属性 -->
              <template v-if="selectedField.type === 'signatureDate'">
                <el-form-item label="签字标签">
                  <el-input v-model="selectedField.value.signatureLabel" />
                </el-form-item>
                <el-form-item label="签字线长度(cm)">
                  <el-input-number v-model="selectedField.value.signatureLineLength" :min="1" :precision="2" controls-position="right" />
                </el-form-item>
                <el-form-item label="日期标签">
                  <el-input v-model="selectedField.value.dateLabel" />
                </el-form-item>
              </template>

              <!-- 横向选项、竖向选项、时间日期组件、文本输入、文本域、粘贴单、图片 使用字段名称 -->
              <el-form-item v-if="selectedField.type === 'horizontalOptions' || selectedField.type === 'verticalOptions' || selectedField.type === 'dateTimeGroup' || selectedField.type === 'textInputField' || selectedField.type === 'textareaField' || selectedField.type === 'pasteUnit' || selectedField.type === 'imageField'" label="字段名称">
                <el-input v-model="selectedField.value.fieldName" @change="handleFieldNameChange" />
              </el-form-item>
              
              <!-- 文本输入特有属性 -->
              <template v-if="selectedField.type === 'textInputField'">
                <el-form-item label="字段格式">
                  <el-input v-model="selectedField.value.fieldFormat" placeholder="例如：3.1, 4.2, 5" />
                </el-form-item>
                
                <el-form-item label="后缀">
                  <el-input v-model="selectedField.value.suffix" placeholder="例如：cm, kg, %" />
                </el-form-item>
              </template>
              
              <!-- 其他组件使用字段标签 -->
              <el-form-item v-else-if="selectedField.type !== 'textareaField' && selectedField.type !== 'dateTimeGroup' && selectedField.type !== 'criteriaTable' && selectedField.type !== 'signatureDate' && selectedField.type !== 'horizontalOptions' && selectedField.type !== 'verticalOptions' && selectedField.type !== 'radioWithInput' && selectedField.type !== 'pasteUnit' && selectedField.type !== 'imageField'" label="字段标签">
                <el-input v-model="selectedField.value.label" />
              </el-form-item>
              


              <!-- 时间日期组件特有属性 - 格式选择 -->
              <template v-if="selectedField.type === 'dateTimeGroup'">
                <el-form-item label="时间格式">
                  <el-select v-model="selectedField.value.dateFormat" placeholder="选择格式">
                    <el-option label="年月日" value="yyyy-mm-dd" />
                    <el-option label="月日" value="mm-dd" />
                    <el-option label="年月日时分" value="yyyy-mm-dd hh:mm" />
                    <el-option label="年月日时分秒" value="yyyy-mm-dd hh:mm:ss" />
                    <el-option label="时分" value="hh:mm" />
                    <el-option label="时分秒" value="hh:mm:ss" />
                    <el-option label="年月日时分秒毫秒" value="yyyy-mm-dd hh:mm:ss.SSS" />
                  </el-select>
                </el-form-item>
                <el-form-item label="后缀">
                  <el-input v-model="selectedField.value.suffix" placeholder="例如：cm, kg, %" />
                </el-form-item>
              </template>

              <!-- 图片特有属性 -->
              <template v-if="selectedField.type === 'imageField'">
                <el-form-item label="前置文字">
                  <el-input v-model="selectedField.value.captionBefore" />
                </el-form-item>
                <el-form-item label="后置文字">
                  <el-input v-model="selectedField.value.captionAfter" />
                </el-form-item>
                <ImageField v-model="selectedField.value" />
                <el-form-item label="对齐">
                  <el-radio-group v-model="selectedField.value.alignment" :default-value="'indent-0'">
                    <el-radio-button label="left">左对齐</el-radio-button>
                    <el-radio-button label="center">居中</el-radio-button>
                    <el-radio-button label="right">右对齐</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </template>

              <!-- 横向选项和竖向选项特有属性 - 选项配置 -->
              <template v-if="selectedField.type === 'horizontalOptions' || selectedField.type === 'verticalOptions'">
                <el-form-item label="选项配置">
                  <div v-for="(option, index) in selectedField.value.options" :key="option.id" class="option-config">
                    <el-input v-model="option.text" placeholder="选项" class="option-label-input" />
                    <el-button 
                      v-if="!option.showLine"
                      type="primary" 
                      link
                      size="small"
                      @click="option.showLine = true"
                    >
                      增加横线
                    </el-button>
                    <template v-else>
                      <el-button 
                        type="warning" 
                        link
                        size="small"
                        @click="option.showLine = false"
                      >
                        移除横线
                      </el-button>
                      <el-input-number 
                        v-model="option.lineLength" 
                        :min="1" 
                        :max="50"
                        :step="1"
                        size="small"
                        controls-position="right"
                        style="width: 80px; margin-left: 8px;"
                      />
                    </template>
                    <el-button 
                      type="danger" 
                      link
                      :disabled="selectedField.value.options.length <= 1"
                      @click="selectedField.value.options.splice(index, 1)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                  <el-button 
                    type="primary" 
                    link
                    @click="selectedField.value.options.push({
                      id: uuidv4(),
                      text: '',
                      showLine: false,
                      lineLength: 10
                    })"
                  >
                    添加选项
                  </el-button>
                </el-form-item>
              </template>
              
              <div style="font-weight: bold; font-size: 14px; margin: 16px 0 8px 0; color: #303133;">样式</div>
              <el-form-item label="缩进">
                <el-radio-group v-model="selectedField.value.alignment" :default-value="'indent-0'" class="indent-radio-group">
                  <el-radio-button label="indent-0">无缩进</el-radio-button>
                  <el-radio-button label="indent-1">1级</el-radio-button>
                  <el-radio-button label="indent-2">2级</el-radio-button>
                  <el-radio-button label="indent-3">3级</el-radio-button>
                  <el-radio-button label="indent-4">4级</el-radio-button>
                  <el-radio-button label="indent-5">5级</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="selectedField.type !== 'criteriaTable'" label="对齐">
                <el-radio-group v-model="selectedField.value.labelAlign" :default-value="'left'">
                  <el-radio-button label="left">左对齐</el-radio-button>
                  <el-radio-button label="center">居中</el-radio-button>
                  <el-radio-button label="right">右对齐</el-radio-button>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="前缀符号" v-if="selectedField.type !== 'criteriaTable'">
                <el-radio-group 
                  v-model="selectedField.value.prefixSymbol" 
                  class="prefix-symbol-group"
                >
                  <el-radio-button label="dot_circle"><span class="symbol-icon">⏺</span></el-radio-button>
                  <el-radio-button label="star"><span class="symbol-icon">✧</span></el-radio-button>
                  <el-radio-button label="pointer"><span class="symbol-icon">☞</span></el-radio-button>
                  <el-radio-button label="arrow_curved"><span class="symbol-icon">⮚</span></el-radio-button>
                  <el-radio-button label="square"><span class="symbol-icon">⯀</span></el-radio-button>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="字体样式" v-if="selectedField.type !== 'criteriaTable'">
                <el-checkbox v-model="selectedField.value.isBold" label="加粗">加粗</el-checkbox>
              </el-form-item>

              <el-form-item label="字体大小" v-if="selectedField.type !== 'criteriaTable'">
                <el-select v-model="selectedField.value.fontSize" placeholder="请选择">
                  <el-option label="小二" value="小二" />
                  <el-option label="小四" value="小四" />
                  <el-option label="五号" value="五号" />
                  <el-option label="小五" value="小五" />
                </el-select>
              </el-form-item>

              <!-- 标准表格：列标题加粗 + 表格字体大小（作为默认/兜底） -->
              <template v-if="selectedField.type === 'criteriaTable'">
                <el-form-item label="列标题加粗">
                  <el-checkbox v-model="selectedField.value.isBold">加粗</el-checkbox>
                </el-form-item>
                <el-form-item label="表格字体大小">
                  <el-select v-model="selectedField.value.fontSize" placeholder="请选择">
                    <el-option label="小二" value="小二" />
                    <el-option label="小四" value="小四" />
                    <el-option label="五号" value="五号" />
                    <el-option label="小五" value="小五" />
                  </el-select>
                </el-form-item>
                <el-form-item label="段落">
                  <el-radio-group v-model="selectedField.value.textAlign" :default-value="'left'">
                    <el-radio-button label="left">左对齐</el-radio-button>
                    <el-radio-button label="center">居中</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </template>

              <!-- 标准表格特有属性 -->
              <template v-if="selectedField.type === 'criteriaTable'">
                <el-form-item label="表头样式">
                  <el-checkbox v-model="selectedField.value.headerShading" :true-label="true" :false-label="false">灰底表头</el-checkbox>
                </el-form-item>
              </template>

              <!-- 文本域特有属性 -->
              <template v-if="selectedField.type === 'textareaField'">
                <el-form-item label="行数">
                  <el-input-number 
                    v-model="selectedField.value.rows" 
                    :min="0"
                    :max="20"
                    controls-position="right"
                  />
                </el-form-item>
              </template>



              <!-- 单选带输入框特有属性 -->
              <template v-if="selectedField.type === 'radioWithInput'">
                <el-form-item label="前置标签">
                  <el-input v-model="selectedField.value.label" />
                </el-form-item>
                
                <el-form-item label="选项配置">
                  <div v-for="(option, index) in selectedField.value.options" :key="index" class="option-config">
                    <el-input v-model="option.label" placeholder="选项文字" class="option-label-input" />
                    <el-input v-model="option.value" placeholder="选项值" class="option-value-input" />
                    <el-switch v-model="option.showInput" active-text="显示输入框" />
                    <el-input 
                      v-if="option.showInput" 
                      v-model="option.inputLabel" 
                      placeholder="输入框标签"
                      class="input-label-input"
                    />
                    <el-button 
                      type="danger" 
                      link
                      :disabled="selectedField.value.options.length <= 1"
                      @click="selectedField.value.options.splice(index, 1)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                  <el-button 
                    type="primary" 
                    link
                    @click="selectedField.value.options.push({
                      label: '新选项',
                      value: uuidv4(),
                      showInput: false,
                      inputLabel: ''
                    })"
                  >
                    添加选项
                  </el-button>
                </el-form-item>
              </template>

              <!-- 粘贴单特有属性 -->
              <template v-if="selectedField.type === 'pasteUnit'">
                <el-form-item label="内部文本">
                  <el-input v-model="selectedField.value.innerText" type="textarea" :rows="2" />
                </el-form-item>
                <el-form-item label="样式类型">
                  <el-select v-model="selectedField.value.styleType">
                    <el-option label="样式1(样本单)" value="style1" />
                    <el-option label="样式2(报告单)" value="style2" />
                  </el-select>
                </el-form-item>
                <el-form-item label="宽度(cm)">
                  <el-input-number v-model="selectedField.value.width" :min="1" :precision="2" controls-position="right" />
                </el-form-item>
                <el-form-item label="高度(cm)">
                  <el-input-number v-model="selectedField.value.height" :min="1" :precision="2" controls-position="right" />
                </el-form-item>
              </template>


              <!-- 签字日期特有属性 -->
              <template v-if="selectedField.type === 'signatureDate'">
                
              </template>


            </el-form>
          </el-card>
        </div>
      </div>
    </el-card>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="表单预览"
      width="80%"
      class="preview-dialog"
      :fullscreen="true"
      :show-close="false"
    >
      <template #header>
        <div class="dialog-header">
          <span>表单预览</span>
          <div class="header-actions">
            <el-button type="primary" @click="previewVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
      <FormPreview ref="previewRef" :fields="formFields" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { v4 as uuidv4 } from 'uuid';
import { 
  ElCard, ElButton, ElButtonGroup, ElIcon, ElDialog, ElForm, ElFormItem, 
  ElInput, ElInputNumber, ElRadioGroup, ElRadioButton, ElSwitch, ElMessageBox, ElMessage, 
  ElCheckTag, ElTooltip 
} from 'element-plus';
import { 
  Document, Calendar, Select, Tickets, Edit, Delete, Plus, ArrowUp, ArrowDown, 
  View, CopyDocument, Rank, Files, Check, Right, Bottom, ScaleToOriginal, Picture
} from '@element-plus/icons-vue';
import { useFormStore } from '@/stores/form';

// 引入所有需要的自定义字段组件
import TextareaField from './types/TextareaField.vue';
import TextInputField from './types/TextInputField.vue';
import DateTimeGroup from './types/DateTimeGroup.vue';
import RadioWithInput from './types/RadioWithInput.vue';


import CriteriaTable from './types/CriteriaTable.vue';

import HorizontalOptions from './types/HorizontalOptions.vue';
import VerticalOptions from './types/VerticalOptions.vue';
import FormPreview from './types/FormPreview.vue';
import PasteUnit from './types/PasteUnit.vue';
import SignatureDateField from './types/SignatureDateField.vue';
import ImageField from './types/ImageField.vue';

// 路由和状态管理
const route = useRoute();
const router = useRouter();
const formStore = useFormStore();

const name = ref('');
// 获取路由参数
name.value = route.query.name;
console.log(name.value)

// 定义props和emit事件
const props = defineProps({
  formData: {
    type: Object,
    default: null
  },
  isEdit: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['saved', 'close']);

// 响应式状态
const formFields = ref([]);
const selectedField = ref(null);
const previewVisible = ref(false);
const canvasRef = ref(null);
const previewRef = ref(null);
const saving = ref(false);
// 导出纸张方向：true 表示横向（landscape），false 表示纵向（portrait）
const isLandscape = ref(false);
// 当前表单是否单页独立（导出时前后分页）
const isSinglePage = ref(false);
// 初始化时从 localStorage 读取偏好
try {
  const saved = localStorage.getItem('export_page_orientation');
  if (saved === 'landscape') {
    isLandscape.value = true;
  }
} catch {}
let draggedField = null;

// 计算属性
const formId = computed(() => props.formData?.id || props.formData?._id || route.params.formId);
const isEditMode = computed(() => props.isEdit || !!formId.value);

// 字段类型定义
const fieldTypes = ref([
  {
    type: 'textInputField',
    label: '文本',
    icon: Edit, 
    defaultValue: {
      fieldName: '', 
      fieldFormat: '0',
      suffix: '',
      alignment: 'indent-0',
      labelAlign: 'left',
      prefixSymbol: '',
      isBold: false,
      fontSize: '五号'
    }
  },
  {
    type: 'textareaField',
    label: '文本域',
    icon: Files, 
    defaultValue: {
      fieldName: '', 
      rows: 3,
      alignment: 'indent-0',
      labelAlign: 'left',
      prefixSymbol: '',
      isBold: false,
      fontSize: '五号'
    }
  },
  {
    type: 'dateTimeGroup',
    label: '日期时间组',
    icon: Calendar,
    defaultValue: {
      fieldName: '',
      dateFormat: 'yyyy-mm-dd hh:mm',
      suffix: '',
      year: null,
      month: null,
      day: null,
      hour: null,
      minute: null,
      second: null,
      millisecond: null,
      alignment: 'indent-0',
      labelAlign: 'left',
      prefixSymbol: '',
      isBold: false,
      fontSize: '五号'
    }
  },

  {
    type: 'criteriaTable',
    label: '标准表格',
    icon: ScaleToOriginal, 
    defaultValue: {
      title: '标准表格',
      headerShading: true,
      fontSize: '五号',
      textAlign: 'left',
      columns: [
        {
          id: 'col_sequence',
          title: '序号',
          type: 'number',
          width: '75px'
        },
        {
          id: 'col_content',
          title: '内容',
          type: 'textarea',
          width: '250px'
        },
        {
          id: 'col_result',
          title: '选项列',
          type: 'checkbox',
          width: '150px',
          options: [
            { label: '是', value: 'yes' },
            { label: '否', value: 'no' }
          ]
        }
      ],
      rows: [],
      note: '',
      alignment: 'indent-0'
    }
  },



  { 
    type: 'horizontalOptions', 
    label: '横向选项', 
    icon: Right, 
    defaultValue: {
      fieldName: '', 
      options: [
        { id: uuidv4(), text: '', showLine: false, lineLength: 10 }
      ], 
      alignment: 'indent-0',
      labelAlign: 'left',
      prefixSymbol: '',
      isBold: false,
      fontSize: '五号'
    } 
  },
  { 
    type: 'verticalOptions', 
    label: '竖向选项', 
    icon: Bottom, 
    defaultValue: {
      fieldName: '', 
      options: [
        { id: uuidv4(), text: '', showLine: false, lineLength: 10 }
      ], 
      alignment: 'indent-0',
      labelAlign: 'left',
      prefixSymbol: '',
      isBold: false,
      fontSize: '五号'
    } 
  },
  {
    type: 'pasteUnit',
    label: '粘贴单',
    icon: Document,
    defaultValue: {
      fieldName: '',
      innerText: '样本编号标签\\n粘贴处',
      styleType: 'style1', // 'style1' | 'style2'
      width: 4, // cm - 样式1默认宽度
      height: 2, // cm - 样式1默认高度
      alignment: 'indent-0',
      labelAlign: 'left',
      prefixSymbol: '',
      isBold: false,
      fontSize: '五号'
    }
  },
  {
    type: 'signatureDate',
    label: '签字/日期',
    icon: CopyDocument,
    defaultValue: {
      signatureLabel: '研究者签字:',
      signatureLineLength: 5, // cm
      dateLabel: '日期: 202',
      alignment: 'indent-0',
      labelAlign: 'left',
      isBold: true,
      fontSize: '五号'
    }
  },
  {
    type: 'imageField',
    label: '图片',
    icon: Picture,
    defaultValue: {
      fieldName: '',
      captionBefore: '',
      captionAfter: '',
      alignment: 'indent-0',
      labelAlign: 'left',
      prefixSymbol: '',
      isBold: false,
      fontSize: '五号',
      image: {
        url: '',
        widthCm: 8,
        heightCm: null,
        maintainAspectRatio: true,
        objectFit: 'contain',
        alt: ''
      }
    }
  }
]);

// 排序：把“图片”移动到“签字/日期”之后
(() => {
  const imgIdx = fieldTypes.value.findIndex(f => f.type === 'imageField');
  const signIdx1 = fieldTypes.value.findIndex(f => f.type === 'signatureDate');
  if (imgIdx > -1 && signIdx1 > -1) {
    const image = fieldTypes.value.splice(imgIdx, 1)[0];
    const signIdx2 = fieldTypes.value.findIndex(f => f.type === 'signatureDate'); // 移除后重算签字索引
    fieldTypes.value.splice(signIdx2 + 1, 0, image);
  }
})();

// 拖拽处理
const handleDragStart = (event, field) => {
  draggedField = field;
  event.dataTransfer.setData('application/json', JSON.stringify(field));
  event.dataTransfer.effectAllowed = 'move';
};

const handleDragEnd = () => {
  draggedField = null;
};

const handleDragEnter = (event) => {
  event.currentTarget.classList.add('drag-over');
};

const handleDragLeave = (event) => {
  event.currentTarget.classList.remove('drag-over');
};

const handleDrop = (event) => {
  event.preventDefault();
  event.currentTarget.classList.remove('drag-over');

  if (draggedField) {
      const newField = {
      id: uuidv4(),
      type: draggedField.type,
      name: `${draggedField.type}_${formFields.value.length + 1}`,
      value: JSON.parse(JSON.stringify(draggedField.defaultValue))
    };
    formFields.value.push(newField);
    handleSelectField(newField);
  }
};

// 字段操作
const handleSelectField = (field) => {
  selectedField.value = field;
};

const handleDeleteField = (index) => {
  if (selectedField.value?.id === formFields.value[index].id) {
    selectedField.value = null;
  }
  formFields.value.splice(index, 1);
};

const handleMoveField = (index, direction) => {
  const newIndex = index + direction;
  if (newIndex >= 0 && newIndex < formFields.value.length) {
    const field = formFields.value.splice(index, 1)[0];
    formFields.value.splice(newIndex, 0, field);
  }
};

// 初始化表单数据
const initFormData = async () => {
  // 如果通过props传入表单数据，直接使用
  if (props.formData?.config?.fields) {
    formFields.value = props.formData.config.fields;
    return;
  }
  
  // 如果是编辑模式且有formId，从后端获取数据
  if (isEditMode.value && formId.value) {
    try {
      const formData = await formStore.fetchForm(formId.value);
      if (formData?.config?.fields) {
        formFields.value = formData.config.fields;
      }
      // 读取单页配置（兼容字符串 'true'）
      const iso = formData?.config?.formConfig?.pageIsolation;
      isSinglePage.value = iso === true || iso === 'true';
      // 读取页面方向（兼容缺省/字符串）
      const ori = formData?.config?.formConfig?.pageOrientation;
      if (ori === 'landscape') {
        isLandscape.value = true;
      } else if (ori === 'portrait') {
        isLandscape.value = false;
      }
      // 设置当前表单到store
      formStore.setCurrentForm(formData);
    } catch (error) {
      console.error('加载表单数据失败:', error);
      ElMessage.error('加载表单数据失败');
    }
  }
};

// 顶部操作
const handleSave = async () => {
  if (saving.value) return;
  
  try {
    saving.value = true;
    
    // 准备保存的数据
    const configData = {
      fields: formFields.value.map(field => ({
        id: field.id,
        type: field.type,
        name: field.name,
        label: field.value?.label || field.value?.fieldName || '未命名字段',
        required: false,
        visible: true,
        value: field.value,
        validations: [],
        fieldConfig: {},
        metadata: {
          createdAt: field.metadata?.createdAt || new Date(),
          updatedAt: new Date(),
          version: (field.metadata?.version || 0) + 1
        }
      })),
      formConfig: {
        pageIsolation: isSinglePage.value,
        pageOrientation: isLandscape.value ? 'landscape' : 'portrait'
      },
      lastUpdated: new Date().toISOString()
    };
    
    if (isEditMode.value && formId.value) {
      // 更新现有表单
      await formStore.updateFormConfig(formId.value, configData);
      ElMessage.success('表单保存成功');
    } else {
      // 创建新表单
      const formData = {
        name: '新表单',
        description: '表单描述',
        type: 'form',
        config: configData
      };
      
      const newForm = await formStore.createForm(formData);
      ElMessage.success('表单创建成功');
    }
    
    // 如果是通过路由打开的，保存成功后自动返回表单列表
    // if (route.params.formId) {
    //   setTimeout(() => {
    //     router.push('/forms');
    //   }, 1500); // 延迟1.5秒让用户看到成功消息
    // } else {
    //   // 如果是通过弹窗打开的，触发保存成功事件
    //   emit('saved');
    // }
  } catch (error) {
    console.error('保存表单失败:', error);
    ElMessage.error(error.message || '保存表单失败');
  } finally {
    saving.value = false;
  }
};

const handlePreview = () => {
  previewVisible.value = true;
};

const handleViewJson = () => {
  ElMessageBox.alert(
    `<pre>${JSON.stringify(formFields.value, null, 2)}</pre>`,
    '表单JSON结构',
    {
      dangerouslyUseHTMLString: true,
      customClass: 'json-message-box'
    }
  );
};

const handleExportDocx = () => {
  if (previewRef.value) {
    previewRef.value.exportDocx();
  }
};

// 复选框变化时持久化
const persistLandscape = () => {
  try {
    localStorage.setItem('export_page_orientation', isLandscape.value ? 'landscape' : 'portrait');
  } catch {}
};

// 标签式开关回调
const setLandscape = (checked) => {
  isLandscape.value = checked;
  persistLandscape();
  // 联动：勾选横向纸张时，自动开启单页
  if (checked && !isSinglePage.value) {
    isSinglePage.value = true;
  }
};

const setSinglePage = (checked) => {
  isSinglePage.value = checked;
};

const handleClose = () => {
  // 如果是通过路由打开的，返回到表单列表
  if (route.params.formId) {
    router.go(-1)
  } else {
    // 如果是通过弹窗打开的，触发关闭事件
    emit('close');
  }
};

const handleFieldNameChange = () => {
  console.log('handleFieldNameChange', selectedField.value.value.fieldName);
  // trim 去除空格
  selectedField.value.value.fieldName = selectedField.value.value.fieldName.trim();
};

// 获取组件类型
const getComponentByType = (type) => {
  const componentMap = {
    'textInputField': TextInputField,
    'textareaField': TextareaField,
    'dateTimeGroup': DateTimeGroup,
    'radioWithInput': RadioWithInput,


    'criteriaTable': CriteriaTable,

    'horizontalOptions': HorizontalOptions,
    'verticalOptions': VerticalOptions,
    'pasteUnit': PasteUnit,
    'signatureDate': SignatureDateField,
    'imageField': ImageField
  };
  return componentMap[type];
};

// 监听props变化，重新初始化数据
watch(() => props.formData, (newFormData) => {
  if (newFormData?.config?.fields) {
    formFields.value = newFormData.config.fields;
  }
}, { deep: true });

// 组件挂载时初始化数据
onMounted(() => {
  initFormData();
});
</script>

<style lang="scss" scoped>
.form-designer {
  height: calc(100vh - 120px);
}

.form-name {
  font-size: 16pt;
  font-weight: bold;
}

.designer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
    
  .header-actions {
    display: inline-flex;
    align-items: center;
    gap: 8px;              /* 与设计规范一致的栅格间距 */
  }

  .header-options {
    display: inline-flex;
    align-items: center;
    gap: 8px;              /* 标签之间 8px */
    margin-right: 12px;    /* 标签组与按钮之间 12px */
  }

  /* 标签式开关统一高度与样式 */
  .header-options :deep(.el-check-tag) {
    height: 32px;                        /* 对齐按钮高度 */
    display: inline-flex;
    align-items: center;
    padding: 0 12px;
    border-radius: 6px;                   /* 轻微圆角更现代 */
    border: 1px solid #dcdfe6;
    background-color: #fff;
    color: #606266;                       /* 与默认文字色一致 */
    font-size: 13px;                      /* 更紧凑的字号 */
    font-weight: 500;
    transition: all .2s ease;
  }

  .header-options :deep(.el-check-tag.is-checked) {
    border-color: #a0cfff;                /* 主色系浅色边框 */
    background-color: #f5f9ff;            /* 更柔和的浅底 */
    color: #409eff;                       /* 主色文案 */
    box-shadow: 0 2px 8px rgba(64,158,255,.08);
  }

  .header-options :deep(.el-icon) {
    margin-right: 6px;
    color: #909399;
  }

  .tag-text {
    font-size: 13px;
  }

  .header-options :deep(.el-check-tag:hover) {
    border-color: #a0cfff;
    background-color: #f7fbff;
  }

  .header-options :deep(.el-check-tag.is-checked .el-icon) {
    color: #409eff;
  }

.designer-content {
      display: flex;
  gap: 16px;
  height: calc(100vh - 200px);
}
    
    .fields-panel {
  width: 240px;
  flex-shrink: 0;

      .fields-list {
    height: 100%;
  }
}

        .field-item {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 10px;
  border: 1px solid #e4e7ed;
          border-radius: 4px;
  margin-bottom: 8px;
          cursor: grab;
  background-color: #fff;
  transition: box-shadow 0.2s, background-color 0.2s;
          
          &:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    background-color: #f5f7fa;
      }
    }
    
    .form-canvas {
  flex-grow: 1;
  padding: 16px;
  border: 1px dashed #dcdfe6;
      border-radius: 4px;
  background-color: #fcfcfc;
  overflow-y: auto;
  position: relative;
  transition: background-color 0.3s;

  &.drag-over {
    background-color: #f0f9eb;
    border-color: #67c23a;
  }
}

.empty-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #909399;
  font-size: 16px;
      }
      
      .form-field {
  padding: 12px;
  border: 1px solid #e4e7ed;
        border-radius: 4px;
  // margin-bottom: 12px;
  background-color: #fff;
  position: relative;
  cursor: pointer;
  transition: border-color 0.2s;
        
        &.is-selected {
    border-color: #409eff;
    box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
          }
        }
        
        .field-actions {
          position: absolute;
  top: 8px;
          right: 8px;
          display: none;
        }
        
.form-field:hover .field-actions {
          display: block;
}

.properties-panel {
  width: 320px;
  flex-shrink: 0;

  .properties-form {
    height: 100%;
    overflow-y: auto;
  }
}

.panel-header {
  font-weight: bold;
}

.option-config {
    display: flex;
    align-items: center;
    gap: 8px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.option-label-input,
.option-value-input {
        width: 120px;
      }
      
.input-label-input {
          width: 150px;
  }
  
.dialog-header {
    display: flex;
  justify-content: space-between;
    align-items: center;
  width: 100%;
}



.symbol-icon {
  font-size: 16px;
  color: #000;
  font-weight: normal;
}

.prefix-symbol-group :deep(.el-radio-button__inner) {
  height: 32px;          /* 统一高度 */
  line-height: 32px;     /* 垂直对齐文本 */
  padding: 0 16px;       /* 内边距统一 */
  display: inline-flex;  /* 图标也能垂直居中 */
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.indent-radio-group {
          display: flex;
  flex-wrap: nowrap;
  
  :deep(.el-radio-button) {
    flex: 1;
    min-width: 45px;
    
    .el-radio-button__inner {
      width: 100%;
      text-align: center;
      padding: 8px 4px;
      font-size: 12px;
      white-space: nowrap;
    }
  }
}

:global(.json-message-box) {
  width: 60%;
}

/* 响应式优化：在较小屏幕上收窄两侧栏，放大中间画布 */
@media (max-width: 1600px) {
  .fields-panel { width: 220px; }
  .properties-panel { width: 300px; }
  .designer-content { gap: 12px; }
}

@media (max-width: 1440px) {
  .fields-panel { width: 200px; }
  .properties-panel { width: 280px; }
  .designer-content { gap: 12px; }
  .form-canvas { padding: 12px; }
  .field-item { padding: 8px; }
}

@media (max-width: 1366px) {
  .fields-panel { width: 180px; }
  .properties-panel { width: 260px; }
  .panel-header { font-size: 12px; }
  .field-item { gap: 6px; }
  .field-item span { font-size: 12px; }
}
</style> 